package com.java.simple.study.juc.p7;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhoujunlin
 * @date 2022年10月17日 22:20
 * @desc
 */
@Slf4j(topic = "c.TestCyclicBarrier")
public class TestCyclicBarrier {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            log.debug("task1, task2 finish");
        });
        for (int i = 0; i < 3; i++) {
            executorService.submit(() -> {
                log.debug("task1 begin...");
                Sleeper.sleep(1);
                try {
                    int await = cyclicBarrier.await();   // 当个数不足时，等待
                    log.debug("task1 await:{}", await);
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });

            executorService.submit(() -> {
                log.debug("task2 begin");
                Sleeper.sleep(2);
                try {
                    int await = cyclicBarrier.await();  // 2 秒后，线程个数够2，继续运行
                    log.debug("task2 await:{}", await);
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
        executorService.shutdown();
    }


}
